import { IAppOption, ICart } from "../../../typings"
import { eventBus } from "../../utils/util"
const app = getApp<IAppOption>()
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    visible: false,
    cartList: [] as ICart[],
    totalPrice: '0.00',
    totalCount: 0,
    cartDrawerVisible: false,
    allSelected: true,
    currentEditItem: null
  },

  lifetimes: {
    attached() {
      // 初始化购物车数据
      this.updateCart()

      // 监听购物车更新事件
      this.updateHandler = () => {
        this.updateCart()
      }
      eventBus.on('cartUpdated', this.updateHandler)
    },

    detached() {
      // 组件销毁时取消监听
      if (this.updateHandler) {
        eventBus.off('cartUpdated', this.updateHandler)
      }
    }
  },
  methods: {
    // 更新购物车数据
    updateCart() {
      const cart = app.globalData.cart || []

      // 如果购物车为空，隐藏胶囊条
      if (cart.length === 0) {
        this.setData({
          visible: false,
          cartDrawerVisible: false
        })
        return
      }

      // 为每个商品添加选中状态和规格文本
      const cartWithSelected = cart.map((item: any) => {
        // 处理规格文本
        let selectedSpecsText = ''
        if (item.selectedSpecs && item.selectedSpecs.length > 0) {
          const specTexts: string[] = []
          item.selectedSpecs.forEach((spec: any) => {
            if (spec.name) {
              specTexts.push(spec.name)
            }
          })
          selectedSpecsText = specTexts.join('，')
        }

        return {
          ...item,
          selected: true,
          selectedSpecsText
        }
      })

      this.setData({
        cartList: cartWithSelected,
        visible: true
      })

      this.calculateTotal()
      this.checkAllSelected()
    },

    // 计算总价和总数
    calculateTotal() {
      const { cartList } = this.data
      let totalPrice = 0
      let totalCount = 0

      cartList.forEach((item: any) => {
        if (item.isSelected) {
          totalPrice += item.price * item.quantity
          totalCount += item.quantity
        }
      })

      this.setData({
        totalPrice: totalPrice.toFixed(2),
        totalCount
      })
    },

    // 检查是否全选
    checkAllSelected() {
      const { cartList } = this.data
      const allSelected = cartList.length > 0 && cartList.every((item: any) => item.isSelected)

      this.setData({
        allSelected
      })
    },

    // 切换购物车抽屉显示状态
    toggleCartDrawer() {
      this.setData({
        cartDrawerVisible: !this.data.cartDrawerVisible
      })
    },

    // 处理购物车抽屉可见性变化
    onCartDrawerVisibleChange(e: any) {
      const { visible } = e.detail
      this.setData({
        cartDrawerVisible: visible
      })
    },

    // 全选/取消全选
    selectAll(e: any) {
      const value = !this.data.allSelected
      const { cartList } = this.data

      console.log("before: " + cartList.map((x) => {
        return JSON.stringify({ id: x._id, isSelected: x.isSelected })
      }));
      const updatedCart = cartList.map((item: any) => ({
        ...item,
        isSelected: value
      }))
      console.log("after: " + updatedCart.map((x) => {
        return JSON.stringify({ id: x._id, isSelected: x.isSelected })
      }));

      this.setData({
        cartList: updatedCart,
        allSelected: value
      })

      this.calculateTotal()
    },

    // 选择商品
    onCheckboxChange(e: any) {
      const id = e.currentTarget.dataset.id
      const { cartList } = this.data
      const index = cartList.findIndex((item: any) => item._id === id)

      if (index > -1) {
        cartList[index].isSelected = !cartList[index].isSelected

        this.setData({
          cartList
        })

        this.calculateTotal()
        this.checkAllSelected()
      }
    },

    // 修改商品数量
    onStepperChange(e: any) {
      const id = e.currentTarget.dataset.id
      const quantity = e.detail.value
      const { cartList } = this.data
      const index = cartList.findIndex((item: any) => item._id === id)

      if (index > -1) {
        const item = cartList[index]
        // 更新全局购物车数据
        app.updateCartItemQuantity(item._id, quantity, item.specsKey)
        // 更新本地数据
        this.updateCart()
      }
    },

    // 从购物车移除商品
    removeFromCart(e: any) {
      const id = e.currentTarget.dataset.id
      const { cartList } = this.data
      const index = cartList.findIndex((item: any) => item._id === id)

      if (index > -1) {
        const item = cartList[index]
        // 更新全局购物车数据
        app.removeFromCart(item._id, item.specsKey)
        // 更新本地数据
        this.updateCart()
      }
    },

    // 清空购物车
    clearCart() {
      wx.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
          if (res.confirm) {
            app.clearCart()
            this.updateCart()
          }
        }
      })
    },

    // 去结算
    checkout() {
      const { cartList } = this.data
      const selectedItems = cartList.filter((item: any) => item.selected)

      if (selectedItems.length === 0) {
        wx.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }

      // 将选中的商品信息存储到全局数据
      if (!app.globalData.checkoutItems) {
        app.globalData.checkoutItems = []
      }
      app.globalData.checkoutItems = selectedItems

      wx.navigateTo({
        url: '/pages/cart/confirm/confirm'
      })
    },

    // 编辑商品规格
    editItemSpecs(e: any) {
      const item = e.currentTarget.dataset.item
      if (!item) return

      // 关闭购物车抽屉
      this.setData({
        cartDrawerVisible: false,
        currentEditItem: item
      })

      // 延迟一下，确保抽屉关闭后再打开规格选择
      setTimeout(() => {
        // 触发规格编辑事件，让页面处理
        eventBus.emit('editItemSpecs', item)
      }, 300)
    }
  }
})